<template>
  <div class="scenic-detail">
    <!-- 顶部图片区域 -->
    <div class="header-images">
      <div class="main-image">
        <img 
          :src="mainImagePath || defaultImage" 
          :alt="attraction?.name"
          @error="handleImageError"
        >
      </div>
      <div class="thumbnail-list">
        <div v-for="(path, index) in thumbnailPaths" :key="index" class="thumbnail">
          <img 
            :src="path" 
            :alt="attraction?.name"
            @error="handleImageError"
          >
        </div>
      </div>
    </div>

    <!-- 景点基本信息 -->
    <div class="info-section">
      <div class="basic-info">
        <h1>{{ attraction?.name || '景点名称' }}</h1>
        <div class="rating">
          <span class="score">{{ attraction?.rating || '0.0' }}</span>
          <span class="total">/5</span>
        </div>
        <div class="tags">
          <span class="tag">{{ attraction?.category || '景点类型' }}</span>
          <span class="tag">{{ attraction?.status === 'open' ? '正在营业' : '暂停营业' }}</span>
          <span class="tag">建议游玩{{ attraction?.recommendedDuration || '2-3小时' }}</span>
        </div>
        <div class="location-info">
          <div class="address">
            <span class="label">地址：</span>
            <span>{{ attraction?.address || '暂无地址信息' }}</span>
          </div>
          <div class="region">
            <span class="label">所在地区：</span>
            <span>{{ attraction?.country || '中国' }} · {{ attraction?.province || '' }} · {{ attraction?.city || '' }}</span>
          </div>
        </div>
        <div class="opening-hours">
          <span class="label">开放时间：</span>
          <span class="time">{{ attraction?.openingHours || '暂无开放时间信息' }}</span>
        </div>
        <div class="contact">
          <span class="label">联系电话：</span>
          <span>{{ attraction?.contactPhone || '暂无联系方式' }}</span>
        </div>
        <div class="description">
          <span class="label">景点简介：</span>
          <p>{{ attraction?.description || '暂无简介' }}</p>
        </div>
        <div class="update-info">
          <p class="small-text">创建时间：{{ attraction?.attractionCreatedAt || '暂无' }}</p>
          <p class="small-text">最后更新：{{ attraction?.lastUpdatedAt || '暂无' }}</p>
        </div>
      </div>

      <!-- 优惠政策 -->
      <div class="policy-section">
        <h2>优惠政策</h2>
        <div class="policy-list">
          <div class="policy-item">
            <div class="type">儿童：</div>
            <div class="content">12岁以下 5-7岁, 免费</div>
          </div>
          <div class="policy-item">
            <div class="type">学生：</div>
            <div class="content">持有效学生证明，优惠</div>
          </div>
          <div class="policy-item">
            <div class="type">老年人：</div>
            <div class="content">65岁以上，优惠</div>
          </div>
          <div class="policy-item">
            <div class="type">特殊说明：</div>
            <div class="content">购买优惠票的游客需要携带有效证件，上述优惠项目不可同时使用，价格部分存在浮动情况</div>
          </div>
        </div>
      </div>
      

      <!-- 服务设施 -->
      <div class="facilities-section">
        <h2>服务设施</h2>
        <div class="facilities-content">
          <p>残障通道：提供残疾人电梯，方便有特殊需求的游客。</p>
          <p>无障碍服务：</p>
          <ul>
            <li>提供轮椅</li>
            <li>无障碍卫生间</li>
            <li>无障碍电梯</li>
          </ul>
        </div>
      </div>

      <!-- 用户点评 -->
      <div class="reviews-section">
        <h2>用户点评 ({{ attraction?.reviewCount || 0 }})</h2>
        <div class="rating-overview">
          <div class="overall-rating">
            <span class="big-score">{{ attraction?.rating || '暂无' }}</span>
            <span class="total">/5</span>
          </div>
          <div class="rating-tags">
            <div class="tag-group">
              <div class="review-tag" @click="activeTab = 'all'">
                <span class="tag-text">全部</span>
                <span class="tag-count">{{ comments.length }}</span>
              </div>
              <div class="review-tag" @click="activeTab = 'good'">
                <span class="tag-text">好评</span>
                <span class="tag-count">{{ goodComments.length }}</span>
              </div>
              <div class="review-tag" @click="activeTab = 'medium'">
                <span class="tag-text">中评</span>
                <span class="tag-count">{{ mediumComments.length }}</span>
              </div>
              <div class="review-tag" @click="activeTab = 'bad'">
                <span class="tag-text">差评</span>
                <span class="tag-count">{{ badComments.length }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 评论区 -->
      <div class="comment-section">
        <!-- 评论输入框 -->
        <div class="comment-input">
          <div class="user-avatar">
            <img :src="defaultImage" alt="用户头像">
          </div>
          <div class="input-wrapper">
            <div class="rating-input">
              <span class="rating-label">评分：</span>
              <el-rate
                v-model="rating"
                :max="5"
                :texts="['1星', '2星', '3星', '4星', '5星']"
                show-text
              />
            </div>
            <div class="discuss-status">
              <span class="status-label">评价类型：</span>
              <el-radio-group v-model="discussStatus">
                <el-radio label="好评">好评</el-radio>
                <el-radio label="中评">中评</el-radio>
                <el-radio label="差评">差评</el-radio>
              </el-radio-group>
            </div>
            <textarea 
              v-model="commentText" 
              placeholder="Hi，楼主等你的回复呢~"
              :maxlength="1000"
              @input="updateCommentLength"
            ></textarea>
            <div class="comment-footer">
              <span class="word-count">{{ commentLength }}/1000</span>
              <button class="submit-btn" @click="submitComment">发表评论</button>
            </div>
          </div>
        </div>

        <!-- 评论列表 -->
        <div class="comment-list">
          <div v-for="comment in filteredComments" :key="comment.id" class="comment-item">
            <div class="user-avatar">
              <img :src="comment.userAvatar || defaultImage" :alt="comment.userName">
            </div>
            <div class="comment-content">
              <div class="comment-header">
                <span class="user-name">{{ comment.userName }}</span>
                <span class="comment-time">发表于 {{ comment.createdAt }}</span>
                <span :class="['discuss-tag', comment.discussStatus]">{{ comment.discussStatus }}</span>
              </div>
              <div class="comment-text">{{ comment.content }}</div>
              <div class="comment-actions">
                <span class="action-btn" @click="replyToComment(comment)">回复</span>
                <span class="action-btn" @click="reportComment(comment)">举报</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 右侧推荐区域 -->
    <div class="sidebar">
      <div class="nearby-spots">
        <h3>附近景点</h3>
        <div class="spot-list">
          <div v-for="spot in nearbySpots" :key="spot.attractionId" class="spot-item">
            <img 
              :src="getImagePath(spot.mainCoverImage)" 
              :alt="spot.name"
              @error="handleImageError"
            >
            <div class="spot-info">
              <h4>{{ spot.name }}</h4>
              <div class="spot-rating">{{ spot.rating }}</div>
              <div class="spot-distance" :class="getDistanceClass(spot.distance)">
                距离景点{{ spot.distance }}km
              </div>
              <div class="spot-category">{{ spot.category }}</div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios';
import { ref, onMounted } from 'vue';

export default {
  name: 'ScenicDetail',
  attractionId: null,
  data() {
    return {
      attraction: {},
      defaultImage: new URL('../imgs/abc.jpg', import.meta.url).href,
      thumbnailImages: [],
      nearbySpots: [],
      commentText: '',
      commentLength: 0,
      comments: [], 
      rating: 5,
      discussStatus: '好评',
      activeTab: 'all',
      // 存储实际的图片路径
      mainImagePath: '',
      thumbnailPaths: [],
    };
  },
  computed: {
    // 好评列表
    goodComments() {
      return this.comments.filter(comment => comment.discussStatus === '好评');
    },
    // 中评列表
    mediumComments() {
      return this.comments.filter(comment => comment.discussStatus === '中评');
    },
    // 差评列表
    badComments() {
      return this.comments.filter(comment => comment.discussStatus === '差评');
    },
    // 根据当前选中的标签过滤评论
    filteredComments() {
      switch (this.activeTab) {
        case 'good':
          return this.goodComments;
        case 'medium':
          return this.mediumComments;
        case 'bad':
          return this.badComments;
        default:
          return this.comments;
      }
    }
  },
  methods: {
    // 处理图片路径 - 支持在线和本地路径
    getImagePath(filename) {
      console.log('处理图片路径:', filename);
      if (!filename) {
        console.log('文件名为空，使用默认图片');
        return this.defaultImage;
      }

      // 检查是否是在线URL
      if (filename.startsWith('http://') || filename.startsWith('https://')) {
        console.log('使用在线图片路径:', filename);
        return filename;
      }

      // 处理本地图片路径
      try {
        return new URL(`../imgs/${filename}`, import.meta.url).href;
      } catch (error) {
        console.error('图片路径生成失败:', error);
        return this.defaultImage;
      }
    },

    // 更新所有图片路径
    updateImagePaths() {
      if (this.attraction?.mainCoverImage) {
        this.mainImagePath = this.getImagePath(this.attraction.mainCoverImage);
      }
      
      if (this.attraction?.images) {
        this.thumbnailPaths = this.attraction.images.map(img => this.getImagePath(img));
      }
    },

    // 计算两点之间的距离（使用Haversine公式）
    calculateDistance(lat1, lon1, lat2, lon2) {
      const R = 6371; // 地球半径（公里）
      const dLat = this.toRad(lat2 - lat1);
      const dLon = this.toRad(lon2 - lon1);
      const a = 
        Math.sin(dLat/2) * Math.sin(dLat/2) +
        Math.cos(this.toRad(lat1)) * Math.cos(this.toRad(lat2)) * 
        Math.sin(dLon/2) * Math.sin(dLon/2);
      const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
      const distance = R * c;
      return Number(distance.toFixed(1)); // 保留一位小数
    },

    // 角度转弧度
    toRad(value) {
      return value * Math.PI / 180;
    },

    // 解析位置字符串
    parseLocation(locationStr) {
      if (!locationStr) return { lat: 0, lon: 0 };
      const [lat, lon] = locationStr.split(',').map(Number);
      return { lat, lon };
    },

    async fetchAttractionDetail() {
      try {
        // 从路径中解析 attractionId
        const path = this.$route.path;
        const idMatch = path.match(/attractionId=(\d+)/);
        const id = idMatch ? idMatch[1] : null;
        console.log('id:', id);
        this.attractionId = id;
        if (!id) {
          console.error('未能获取到景点ID');
          return;
        }

        // 构造请求参数
        const searchParams = {
          attractionId:id
        };
        
        console.log('发送请求参数:', searchParams);
        const response = await axios.post('/scenicspot/getAttractionDetail',searchParams);
        console.log('接收到响应:', response.data);
        this.attraction = response.data;
        if (response.data?.hits?.hits?.length > 0) {
          this.attraction = response.data.hits.hits[0]._source;
          if (this.attraction?.images?.length > 0) {
            this.thumbnailImages = this.attraction.images;
          }
        }
        // 获取数据后更新图片路径
        this.updateImagePaths();
      } catch (error) {
        console.error('获取景点详情失败:', error);
      }
    },
    async fetchNearbyAttractions() {
      try {
        let id = this.attractionId;
        const response = await axios.post('/scenicspot/getNearbyAttractionsById',
          {attractionId:id}
        );
        
        // 获取当前景点的位置
        const currentLocation = this.parseLocation(this.attraction.location);
        
        // 处理附近景点数据，计算距离
        this.nearbySpots = response.data.map(spot => {
          const spotLocation = this.parseLocation(spot.location);
          const distance = this.calculateDistance(
            currentLocation.lat,
            currentLocation.lon,
            spotLocation.lat,
            spotLocation.lon
          );
          return {
            ...spot,
            distance // 添加距离字段
          };
        });

        // 按距离排序
        this.nearbySpots.sort((a, b) => a.distance - b.distance);
        
        console.log('获取附近景点:', this.nearbySpots);
        // 获取数据后更新图片路径
        this.updateImagePaths();
      } catch (error) {
        console.error('获取附近景点失败:', error);
      }
    },

    // 更新评论字数
    updateCommentLength() {
      this.commentLength = this.commentText.length;
    },

    // 提交评论
    async submitComment() {
      if (!this.commentText.trim()) {
        this.$message.warning('评论内容不能为空');
        return;
      }

      try {
        const reviewData = {
          attractionId: this.attractionId,
          content: this.commentText,
          rating: this.rating,
          discussStatus: this.discussStatus,
          userName: localStorage.getItem('userName') || '游客', // 从本地存储获取用户名
          createdAt: new Date().toLocaleString() // 添加创建时间
        };

        console.log('提交评论数据:', reviewData);
        const response = await axios.post('/comment/add', reviewData);
        console.log('评论提交响应:', response);
        if (response.code === 200) {
          this.$message.success('评论发表成功');
          // 清空评论框
          this.commentText = '';
          this.commentLength = 0;
          // 重新获取评论列表
          this.fetchComments();
        } else {
          this.$message.error(response.data.msg || '添加失败');
        }
      } catch (error) {
        console.error('提交评论失败:', error);
        this.$message.error('评论发表失败，请稍后重试');
      }
    },

    // 获取评论列表
    async fetchComments() {
      try {
        const response = await axios.post('/comment/getReviewsById', {
          attractionId: this.attractionId,
          pageNum: 1,
          pageSize: 10
        });
        console.log('获取评论列表:', response.data.records);
        this.comments = response.data.records;
      } catch (error) {
        console.error('获取评论列表失败:', error);
      }
    },

    // 回复评论
    replyToComment(comment) {
      this.commentText = `回复 @${comment.userName}：`;
      // 聚焦到评论输入框
      document.querySelector('.comment-input textarea').focus();
    },

    // 举报评论
    reportComment(comment) {
      // 实现举报功能
      console.log('举报评论:', comment);
    },

    // 处理标签切换
    handleTabClick(tab) {
      this.activeTab = tab.name;
    },

    // 根据距离返回不同的样式类
    getDistanceClass(distance) {
      if (distance <= 1) return 'distance-near';
      if (distance <= 3) return 'distance-medium';
      return 'distance-far';
    },

    // 处理图片加载失败
    handleImageError(event) {
      console.log('图片加载失败，原始src:', event.target.src);
      console.log('切换到默认图片');
      // 如果加载失败的是在线图片，也使用默认图片
      event.target.src = this.defaultImage;
    }
  },
  async created() {
    await this.fetchAttractionDetail();
    await this.fetchNearbyAttractions();
    await this.fetchComments();
    await this.updateImagePaths(); // 初始化所有图片路径
  }
};
</script>

<style scoped>
.scenic-detail {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  display: grid;
  grid-template-columns: 1fr 300px;
  gap: 20px;
}

.header-images {
  grid-column: 1 / -1;
}

.main-image {
  width: 100%;
  height: 400px;
  overflow: hidden;
  border-radius: 8px;
  margin-bottom: 10px;
}

.main-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.thumbnail-list {
  display: flex;
  gap: 10px;
}

.thumbnail {
  width: 100px;
  height: 100px;
  overflow: hidden;
  border-radius: 4px;
}

.thumbnail img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.info-section {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.basic-info h1 {
  font-size: 24px;
  margin: 0 0 10px;
}

.rating {
  margin: 10px 0;
}

.score {
  font-size: 20px;
  color: #ff9800;
  font-weight: bold;
}

.total-reviews {
  color: #666;
}

.tags {
  margin: 10px 0;
}

.tag {
  background: #f5f5f5;
  padding: 4px 8px;
  border-radius: 4px;
  margin-right: 8px;
  font-size: 12px;
}

.address, .opening-hours, .contact {
  margin: 10px 0;
  color: #666;
}

.label {
  color: #333;
  font-weight: bold;
}

.policy-section, .facilities-section, .reviews-section {
  margin-top: 30px;
  border-top: 1px solid #eee;
  padding-top: 20px;
}

h2 {
  font-size: 18px;
  margin-bottom: 15px;
}

.policy-item {
  display: flex;
  margin-bottom: 10px;
}

.policy-item .type {
  width: 80px;
  color: #333;
  font-weight: bold;
}

.facilities-content {
  color: #666;
  line-height: 1.6;
}

.facilities-content ul {
  list-style: none;
  padding-left: 20px;
}

.rating-overview {
  display: flex;
  align-items: center;
  gap: 20px;
}

.overall-rating {
  font-size: 32px;
  color: #ff9800;
}

.rating-tags {
  margin: 20px 0;
}

.tag-group {
  display: flex;
  gap: 20px;
}

.review-tag {
  position: relative;
  cursor: pointer;
  padding: 5px 15px;
  border-radius: 4px;
  background: #f5f5f5;
  transition: all 0.3s;
}

.review-tag:hover {
  background: #e8e8e8;
}

.tag-text {
  font-size: 14px;
  color: #333;
}

.tag-count {
  position: absolute;
  top: -8px;
  right: -8px;
  background: #ff6b6b;
  color: white;
  font-size: 12px;
  padding: 2px 6px;
  border-radius: 10px;
  min-width: 20px;
  text-align: center;
}

.review-tag.active {
  background: #e8f4ff;
  color: #1890ff;
}

.review-tag.active .tag-count {
  background: #1890ff;
}

.discuss-tag {
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
  margin-left: 10px;
}

.discuss-tag.好评 {
  background-color: #f0f9eb;
  color: #67c23a;
}

.discuss-tag.中评 {
  background-color: #fdf6ec;
  color: #e6a23c;
}

.discuss-tag.差评 {
  background-color: #fef0f0;
  color: #f56c6c;
}

.el-tabs {
  margin-bottom: 20px;
}

.sidebar {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.spot-item {
  display: flex;
  gap: 10px;
  margin-bottom: 15px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}

.spot-item img {
  width: 80px;
  height: 80px;
  border-radius: 4px;
  object-fit: cover;
}

.spot-info h4 {
  margin: 0 0 5px;
  font-size: 14px;
}

.spot-rating {
  color: #ff9800;
  font-weight: bold;
}

.spot-distance {
  font-size: 12px;
  margin: 4px 0;
}

.distance-near {
  color: #67c23a;
}

.distance-medium {
  color: #e6a23c;
}

.distance-far {
  color: #f56c6c;
}

.spot-category {
  font-size: 12px;
  color: #666;
  margin-top: 4px;
  background: #f5f5f5;
  padding: 2px 6px;
  border-radius: 3px;
  display: inline-block;
}

/* 评论区样式 */
.comment-section {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #eee;
}

.comment-input {
  display: flex;
  gap: 15px;
  margin-bottom: 20px;
}

.user-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  overflow: hidden;
  flex-shrink: 0;
}

.user-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.input-wrapper {
  flex: 1;
}

.rating-input {
  margin-bottom: 15px;
}

.rating-label, .status-label {
  font-size: 14px;
  color: #333;
  margin-right: 10px;
}

.discuss-status {
  margin-bottom: 15px;
}

.el-radio-group {
  margin-top: 5px;
}

.el-radio {
  margin-right: 20px;
}

.input-wrapper textarea {
  width: 100%;
  height: 100px;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  resize: none;
  font-size: 14px;
  transition: all 0.3s;
}

.input-wrapper textarea:focus {
  border-color: #1890ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
  outline: none;
}

.comment-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 10px;
}

.word-count {
  color: #999;
  font-size: 12px;
}

.submit-btn {
  padding: 6px 16px;
  background: #ff6600;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.submit-btn:hover {
  background: #ff8533;
}

.comment-list {
  margin-top: 20px;
}

.comment-item {
  display: flex;
  gap: 15px;
  padding: 15px 0;
  border-bottom: 1px solid #f0f0f0;
}

.comment-content {
  flex: 1;
}

.comment-header {
  margin-bottom: 8px;
}

.user-name {
  font-weight: 500;
  color: #333;
  margin-right: 10px;
}

.comment-time {
  color: #999;
  font-size: 12px;
}

.comment-text {
  font-size: 14px;
  line-height: 1.6;
  color: #333;
  margin-bottom: 8px;
}

.comment-actions {
  display: flex;
  gap: 15px;
}

.action-btn {
  color: #666;
  font-size: 12px;
  cursor: pointer;
}

.action-btn:hover {
  color: #1890ff;
}
</style>
